package com.sx.dao.daoImpl;

import com.sx.dao.GoodRecordDao;
import com.sx.pojo.GoodsOpRecords;
import com.sx.utils.DatabaseUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class GoodRecordDaoImpl implements GoodRecordDao {

    private static final Logger logger = LogManager.getLogger(GoodRecordDaoImpl.class);
    @Override
    public ArrayList<GoodsOpRecords> getAllGoodRecords() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        GoodsOpRecords goods;
        ArrayList<GoodsOpRecords> goodsList = new ArrayList<>();
        try {
            connection = DatabaseUtil.getConnection();
            if (connection != null) {
                String sql = "SELECT person_name, xgood, ygood FROM goodsoprecords";
                statement = connection.prepareStatement(sql);
                resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    goods = new GoodsOpRecords();
                    goods.setPersonName(resultSet.getString("person_name"));
                    goods.setXGood(formatGoodInfo(resultSet.getString("xgood")));
                    goods.setYGood(formatGoodInfo(resultSet.getString("ygood")));
                    goodsList.add(goods);
                }
            } else {
                logger.error("数据库连接失败");
            }
        } catch (Exception e) {
            logger.error("获取日志列表失败: {}", e.getMessage(), e);
        } finally {
            try {
                if (resultSet != null) resultSet.close();
                if (statement != null) statement.close();
                if (connection != null) connection.close();
            } catch (Exception e) {
                logger.error("关闭资源异常: {}", e.getMessage(), e);
            }
        }
        logger.info("查询到日志：{}", goodsList.size());
        return goodsList;
    }

    private String formatGoodInfo(String goodInfo) {
        if (goodInfo == null || goodInfo.isEmpty()) {
            return "";
        }
        // 假设 goodInfo 格式为 "Name=xxx, Price=yyy, Description=zzz"
        String name = goodInfo.substring(goodInfo.indexOf("Name=") + 5, goodInfo.indexOf(", Price="));
        String price = goodInfo.substring(goodInfo.indexOf("Price=") + 6, goodInfo.indexOf(", Description="));
        String description = goodInfo.substring(goodInfo.indexOf("Description=") + 12,goodInfo.indexOf(", InPrice="));
        return String.format("名称: %s, 价格: %s, 描述: %s", name, price, description);
    }

}
